#!/bin/sh
#
# shell script to create Bacula SQLite tables
#
# Copyright (C) 2000-2023 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#

bindir=@SQLITE_BINDIR@
PATH="$bindir:$PATH"
cd @working_dir@
db_name=@db_name@

sqlite3 $* ${db_name}.db <<END-OF-DATA
-- --------------------------------------------------------------

CREATE TABLE MalwareMD5
(
    MD5     char(22)    -- Same as File
);
CREATE INDEX malwaremd5_idx on MalwareMD5 (MD5);

CREATE TABLE MalwareSHA256
(
    MD5     char(65)    -- Same as File
);
CREATE INDEX malwaresha256_idx on MalwareSHA256 (MD5);

CREATE TABLE FileEvents 
(
   Id	  INTEGER PRIMARY KEY AUTOINCREMENT,
   Time  DATETIME DEFAULT current_timestamp, -- Time of the detection
   SourceJobId   int,        -- Can be the Verify job id for example, or the jobid during a restore/backup
   JobId         int,        -- JobId where the file was found. Used for pruning
   FileIndex     int,        -- File reference
   Type          char,       -- Event type (antivirus, malware scanning (M), lost file)
   Description   text,       -- Description of the event
   Severity      int,        -- level of severity. (0 OK, 100 Important)
   Source        text        -- Information about the source of the event
);

CREATE INDEX FileEvents_jobid_idx ON FileEvents (JobId, FileIndex);
CREATE INDEX FileEvents_sourcejobid_idx ON FileEvents (SourceJobId);

-- MetaData Index

CREATE TABLE MetaEmail
(
    EmailTenant       		text,
    EmailOwner        		text,
    EmailId           		text,
    EmailTime 			DATETIME,
    EmailTags         		text,
    EmailSubject      		text,
    EmailFolderName   		text,
    EmailFrom         		text,
    EmailTo           		text,
    EmailCc     		    text,
    EmailInternetMessageId 	text,  -- no index
    EmailBodyPreview  		text,
    EmailImportance   		text,
    EmailConversationId    	text,
    EmailIsRead       		smallint,
    EmailIsDraft      		smallint,
    EmailHasAttachment	 	smallint,
    EmailSize    			integer,
    Plugin      			text,
    FileIndex  				int,
    JobId        			int
);

CREATE INDEX meta_emailowner on MetaEmail (EmailTenant, EmailOwner);
CREATE INDEX meta_emailtime on MetaEmail (EmailTime);
CREATE INDEX meta_emailid on MetaEmail (EmailId);
CREATE INDEX meta_emailtags on MetaEmail (EmailTags);
CREATE INDEX meta_emailfoldername on MetaEmail (EmailFolderName);
-- CREATE INDEX meta_emailsender on MetaEmail (EmailSender);
CREATE INDEX meta_emailconversationid on MetaEmail (EmailConversationId);
-- TODO: Implement search op in SQLite
CREATE INDEX meta_emailimportance on MetaEmail (EmailImportance);
CREATE INDEX meta_emailisread on MetaEmail (EmailIsRead);
CREATE INDEX meta_emailhasattachment on MetaEmail (EmailHasAttachment);
CREATE INDEX meta_emailjobid on MetaEmail (Jobid);

CREATE TABLE MetaAttachment
(
    AttachmentTenant            text,
    AttachmentOwner    		text,
    AttachmentName     		text,
    AttachmentEmailId  		text,
    AttachmentContentType 	text,
    AttachmentIsInline 		smallint,
    AttachmentSize    		int,
    Plugin       			text,
    FileIndex    			int,
    JobId        			int
);

CREATE INDEX meta_attachmentowner ON MetaAttachment (AttachmentTenant,AttachmentOwner);
CREATE INDEX meta_attachmentemailid ON MetaAttachment (AttachmentEmailId);
CREATE INDEX meta_attachmentjobid ON MetaAttachment (JobId); 

CREATE TABLE TagJob
(
   JobId integer not null,
   Tag   text    not null,
   primary key (JobId, Tag)
);

CREATE TABLE TagClient
(
   ClientId integer not null,
   Tag      text    not null,
   primary key (ClientId, Tag)
);

CREATE TABLE TagMedia
(
   MediaId integer not null,
   Tag      text    not null,
   primary key (MediaId, Tag)
);

CREATE TABLE TagObject
(
   ObjectId integer not null,
   Tag      text    not null,
   primary key (ObjectId, Tag)
);

CREATE TABLE Object
(
   ObjectId     integer  not null,

   JobId        integer  not null,
   Path         text     not null,
   Filename     text     not null,
   PluginName   text     not null,
   FileIndex    integer  not null default 0,

   ObjectCategory  text     not null,
   ObjectType      text     not null,
   ObjectName      text     not null,
   ObjectSource    text     not null,
   ObjectUUID      text     not null,
   ObjectSize      integer  not null,
   ObjectStatus    char(1)  not null default 'U',
   ObjectCount     integer  not null default 1,
   primary key (ObjectId)
);

create index object_jobid_idx on Object (JobId);
create index object_category_idx on Object (ObjectCategory);
create index object_type_idx on Object  (ObjectType);
create index object_name_idx on Object  (ObjectName);
create index object_source_idx on Object  (ObjectSource);

CREATE TABLE Events
(
    EventsId          INTEGER,
    EventsCode        text        not null,
    EventsType	      text	  not null,
    EventsTime	      DATETIME,
    EventsInsertTime  DATETIME DEFAULT current_timestamp,
    EventsDaemon        text        default '',
    EventsSource      text        default '',
    EventsRef         text        default '',
    EventsText	      text	  not null,
    primary key (EventsId)
);
create index events_time_idx on Events (EventsTime);

CREATE TABLE Path (
   PathId INTEGER,
   Path TEXT DEFAULT '',
   PRIMARY KEY(PathId) 
   );

CREATE INDEX inx2 ON Path (Path);

-- In File table
-- FileIndex can be 0 for FT_DELETED files
-- FileName can be '' for directories
CREATE TABLE File (
   FileId INTEGER,
   FileIndex INTEGER DEFAULT 0,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PathId INTEGER UNSIGNED REFERENCES Path NOT NULL,
   Filename TEXT NOT NULL DEFAULT '',
   DeltaSeq SMALLINT UNSIGNED DEFAULT 0,
   MarkId INTEGER UNSIGNED DEFAULT 0,
   LStat VARCHAR(255) NOT NULL,
   MD5 VARCHAR(255) NOT NULL,
   PRIMARY KEY(FileId) 
   );
CREATE INDEX inx3 ON File (JobId);
CREATE INDEX file_jpf_idx ON File (JobId, PathId, Filename);
--
-- Possibly add one or more of the following indexes
--  if your Verifies are too slow.
--
-- CREATE INDEX inx4 ON File (PathId);
-- CREATE INDEX inx5 ON File (FileName);


CREATE TABLE RestoreObject (
   RestoreObjectId INTEGER,
   ObjectName TEXT DEFAULT '',
   RestoreObject TEXT DEFAULT '',
   PluginName TEXT DEFAULT '',
   ObjectLength INTEGER DEFAULT 0,
   ObjectFullLength INTEGER DEFAULT 0,
   ObjectIndex INTEGER DEFAULT 0,
   ObjectType INTEGER DEFAULT 0,
   FileIndex INTEGER DEFAULT 0,
   ObjectCompression INTEGER DEFAULT 0,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PRIMARY KEY(RestoreObjectId)
   );
CREATE INDEX restore_jobid_idx ON RestoreObject (JobId);


CREATE TABLE Job (
   JobId INTEGER PRIMARY KEY AUTOINCREMENT,
   Job VARCHAR(128) NOT NULL,
   Name VARCHAR(128) NOT NULL,
   Type CHAR(1) NOT NULL,
   Level CHAR(1) NOT NULL,
   ClientId INTEGER REFERENCES Client DEFAULT 0,
   JobStatus CHAR(1) NOT NULL,
   SchedTime DATETIME NOT NULL,
   StartTime DATETIME DEFAULT 0,
   EndTime DATETIME DEFAULT 0,
   RealEndTime DATETIME DEFAULT 0,
   RealStartTime DATETIME DEFAULT 0, -- Time of the job for Virtual Full
   JobTDate BIGINT UNSIGNED DEFAULT 0,
   VolSessionId INTEGER UNSIGNED DEFAULT 0,
   VolSessionTime INTEGER UNSIGNED DEFAULT 0,
   JobFiles INTEGER UNSIGNED DEFAULT 0,
   JobBytes BIGINT UNSIGNED DEFAULT 0,
   ReadBytes BIGINT UNSIGNED DEFAULT 0,
   JobErrors INTEGER UNSIGNED DEFAULT 0,
   JobMissingFiles INTEGER UNSIGNED DEFAULT 0,
   PoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   FileSetId INTEGER UNSIGNED REFERENCES FileSet DEFAULT 0,
   PriorJobId INTEGER UNSIGNED REFERENCES Job DEFAULT 0,
   PriorJob VARCHAR(128) DEFAULT '',
   PurgedFiles TINYINT DEFAULT 0,
   HasBase TINYINT DEFAULT 0,
   HasCache TINYINT DEFAULT 0,
   Reviewed TINYINT DEFAULT 0,
   Comment TEXT,
   FileTable TEXT DEFAULT 'File',
   isVirtualFull     TINYINT     default 0,   -- Result of a VirtualFull?
   CompressRatio     float       default 0,   -- Compression Ratio
   Rate              float       default 0,   -- Job Rate B/s
   LastReadStorageId integer     default 0,   -- Id of the last Storage used to Read
   LastReadDevice    text        default '',  -- Name of the last Read Device
   WriteStorageId    integer     default 0,   -- Id of the Storage used to Write
   WriteDevice       text        default '',  -- Name of the Write Device
   StatusInfo        text        default '',  -- Info to determine the error status
   Encrypted         int         default 0   -- 0 no, 1 fd side, 2 sd side, 3 both
   );
CREATE INDEX inx6 ON Job (Name);

-- Create a table like Job for long term statistics 
CREATE TABLE JobHisto (
   JobId INTEGER,
   Job VARCHAR(128) NOT NULL,
   Name VARCHAR(128) NOT NULL,
   Type CHAR(1) NOT NULL,
   Level CHAR(1) NOT NULL,
   ClientId INTEGER DEFAULT 0,
   JobStatus CHAR(1) NOT NULL,
   SchedTime DATETIME NOT NULL,
   StartTime DATETIME DEFAULT 0,
   EndTime DATETIME DEFAULT 0,
   RealEndTime DATETIME DEFAULT 0,
   RealStartTime     DATETIME DEFAULT 0,
   JobTDate BIGINT UNSIGNED DEFAULT 0,
   VolSessionId INTEGER UNSIGNED DEFAULT 0,
   VolSessionTime INTEGER UNSIGNED DEFAULT 0,
   JobFiles INTEGER UNSIGNED DEFAULT 0,
   JobBytes BIGINT UNSIGNED DEFAULT 0,
   ReadBytes BIGINT UNSIGNED DEFAULT 0,
   JobErrors INTEGER UNSIGNED DEFAULT 0,
   JobMissingFiles INTEGER UNSIGNED DEFAULT 0,
   PoolId INTEGER UNSIGNED DEFAULT 0,
   FileSetId INTEGER UNSIGNED DEFAULT 0,
   PriorJobId INTEGER UNSIGNED DEFAULT 0,
   PriorJob VARCHAR(128) DEFAULT '',
   PurgedFiles TINYINT DEFAULT 0,
   HasBase TINYINT DEFAULT 0,
   HasCache TINYINT DEFAULT 0,
   Reviewed TINYINT DEFAULT 0,
   Comment TEXT,
   FileTable TEXT DEFAULT 'File',
   isVirtualFull     TINYINT     default 0,   -- Result of a VirtualFull?
   CompressRatio     float       default 0,   -- Compression Ratio
   Rate              float       default 0,   -- Job Rate B/s
   LastReadStorageId integer     default 0,   -- Id of the last Storage used to Read
   LastReadDevice    text        default '',  -- Name of the last Read Device
   WriteStorageId    integer     default 0,   -- Id of the Storage used to Write
   WriteDevice       text        default '',  -- Name of the Write Device
   StatusInfo        text        default '',  -- Info to determine the error status
   Encrypted         int         default 0    -- 0 no, 1 fd side, 2 sd side, 3 both
   );
CREATE INDEX inx61 ON JobHisto (StartTime);

CREATE TABLE Location (
   LocationId INTEGER,
   Location TEXT NOT NULL,
   Cost INTEGER DEFAULT 0,
   Enabled TINYINT,
   PRIMARY KEY(LocationId)
   );

CREATE TABLE LocationLog (
   LocLogId INTEGER,
   Date DATETIME NOT NULL,
   Comment TEXT NOT NULL,
   MediaId INTEGER UNSIGNED REFERENCES Media DEFAULT 0,
   LocationId INTEGER UNSIGNED REFERENCES LocationId DEFAULT 0,
   NewVolStatus VARCHAR(20) NOT NULL,
   NewEnabled TINYINT NOT NULL,
   PRIMARY KEY(LocLogId)
);


CREATE TABLE Log (
   LogId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   Time DATETIME NOT NULL,
   LogText TEXT NOT NULL,
   PRIMARY KEY(LogId) 
   );
CREATE INDEX LogInx1 ON Log (JobId);


CREATE TABLE FileSet (
   FileSetId INTEGER,
   FileSet VARCHAR(128) NOT NULL,
   MD5 VARCHAR(25) NOT NULL,
   CreateTime DATETIME DEFAULT 0,
   Content TEXT DEFAULT '',
   PRIMARY KEY(FileSetId)
   );

CREATE TABLE JobMedia (
   JobMediaId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   MediaId INTEGER UNSIGNED REFERENCES Media NOT NULL,
   FirstIndex INTEGER UNSIGNED NOT NULL,
   LastIndex INTEGER UNSIGNED NOT NULL,
   StartFile INTEGER UNSIGNED DEFAULT 0,
   EndFile INTEGER UNSIGNED DEFAULT 0,
   StartBlock INTEGER UNSIGNED DEFAULT 0,
   EndBlock INTEGER UNSIGNED DEFAULT 0,
   VolIndex INTEGER UNSIGNED DEFAULT 0,
   PRIMARY KEY(JobMediaId) 
   );

CREATE INDEX inx7 ON JobMedia (JobId, MediaId);
CREATE INDEX inx71 ON JobMedia (MediaId);

CREATE TABLE FileMedia
(
    JobId	      integer	  not null,
    FileIndex	      integer	  not null,
    MediaId	      integer	  not null,
    BlockAddress      bigint	  default 0,
    RecordNo	      integer	  default 0,
    FileOffset	      bigint	  default 0
);
CREATE INDEX file_media_idx on FileMedia (JobId, FileIndex);

CREATE TABLE Media (
   MediaId INTEGER,
   VolumeName VARCHAR(128) NOT NULL,
   Slot INTEGER DEFAULT 0,
   PoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   MediaType VARCHAR(128) NOT NULL,
   MediaTypeId INTEGER UNSIGNED REFERENCES MediaType DEFAULT 0,
   LabelType TINYINT DEFAULT 0,
   FirstWritten DATETIME DEFAULT 0,
   LastWritten DATETIME DEFAULT 0,
   LabelDate DATETIME DEFAULT 0,
   VolJobs INTEGER UNSIGNED DEFAULT 0,
   VolFiles INTEGER UNSIGNED DEFAULT 0,
   VolBlocks INTEGER UNSIGNED DEFAULT 0,
   LastPartBytes BIGINT UNSIGNED DEFAULT 0,
   VolMounts INTEGER UNSIGNED DEFAULT 0,
   VolBytes BIGINT UNSIGNED DEFAULT 0,
   VolABytes BIGINT UNSIGNED DEFAULT 0,
   VolAPadding BIGINT UNSIGNED DEFAULT 0,
   VolHoleBytes BIGINT UNSIGNED DEFAULT 0,
   VolHoles INTEGER UNSIGNED DEFAULT 0,
   VolType INTEGER UNSIGNED DEFAULT 0,
   VolParts INTEGER UNSIGNED DEFAULT 0,
   VolCloudParts INTEGER UNSIGNED DEFAULT 0,
   VolErrors INTEGER UNSIGNED DEFAULT 0,
   VolWrites BIGINT UNSIGNED DEFAULT 0,
   VolCapacityBytes BIGINT UNSIGNED DEFAULT 0,
   VolStatus VARCHAR(20) NOT NULL,
   Enabled TINYINT DEFAULT 1,
   Recycle TINYINT DEFAULT 0,
   ActionOnPurge     TINYINT	DEFAULT 0,
   CacheRetention BIGINT UNSIGNED DEFAULT 0,
   VolRetention BIGINT UNSIGNED DEFAULT 0,
   VolUseDuration BIGINT UNSIGNED DEFAULT 0,
   MaxVolJobs INTEGER UNSIGNED DEFAULT 0,
   MaxVolFiles INTEGER UNSIGNED DEFAULT 0,
   MaxVolBytes BIGINT UNSIGNED DEFAULT 0,
   InChanger TINYINT DEFAULT 0,
   StorageId INTEGER UNSIGNED REFERENCES Storage DEFAULT 0,
   DeviceId INTEGER UNSIGNED REFERENCES Device DEFAULT 0,
   MediaAddressing TINYINT DEFAULT 0,
   VolReadTime BIGINT UNSIGNED DEFAULT 0,
   VolWriteTime BIGINT UNSIGNED DEFAULT 0,
   EndFile INTEGER UNSIGNED DEFAULT 0,
   EndBlock INTEGER UNSIGNED DEFAULT 0,
   LocationId INTEGER UNSIGNED REFERENCES Location DEFAULT 0,
   RecycleCount INTEGER UNSIGNED DEFAULT 0,
   InitialWrite DATETIME DEFAULT 0,
   ScratchPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   RecyclePoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   Comment TEXT,
   Protected TINYINT DEFAULT 0,
   UseProtect TINYINT DEFAULT 0,
   VolEncrypted TINYINT DEFAULT 0,
   PRIMARY KEY(MediaId)
   );

CREATE INDEX inx8 ON Media (PoolId);
CREATE INDEX inx9 ON Media (StorageId);


CREATE TABLE MediaType (
   MediaTypeId INTEGER,
   MediaType VARCHAR(128) NOT NULL,
   ReadOnly TINYINT DEFAULT 0,
   PRIMARY KEY(MediaTypeId)
   );

CREATE TABLE Storage (
   StorageId INTEGER,
   Name VARCHAR(128) NOT NULL,
   AutoChanger TINYINT DEFAULT 0,
   PRIMARY KEY(StorageId)
   );

CREATE TABLE Device (
   DeviceId INTEGER,
   Name VARCHAR(128) NOT NULL,
   MediaTypeId INTEGER UNSIGNED REFERENCES MediaType NOT NULL,
   StorageId INTEGER UNSIGNED REFERENCES Storage,
   DevMounts INTEGER UNSIGNED DEFAULT 0,
   DevReadBytes BIGINT UNSIGNED DEFAULT 0,
   DevWriteBytes BIGINT UNSIGNED DEFAULT 0,
   DevReadBytesSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevWriteBytesSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevReadTime BIGINT UNSIGNED DEFAULT 0,
   DevWriteTime BIGINT UNSIGNED DEFAULT 0,
   DevReadTimeSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevWriteTimeSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   CleaningDate DATETIME DEFAULT 0,
   CleaningPeriod BIGINT UNSIGNED DEFAULT 0,
   PRIMARY KEY(DeviceId)
   );


CREATE TABLE Pool (
   PoolId INTEGER,
   Name VARCHAR(128) NOT NULL,
   NumVols INTEGER UNSIGNED DEFAULT 0,
   MaxVols INTEGER UNSIGNED DEFAULT 0,
   UseOnce TINYINT DEFAULT 0,
   UseCatalog TINYINT DEFAULT 1,
   AcceptAnyVolume TINYINT DEFAULT 0,
   VolRetention BIGINT UNSIGNED DEFAULT 0,
   CacheRetention BIGINT UNSIGNED DEFAULT 0,
   VolUseDuration BIGINT UNSIGNED DEFAULT 0,
   MaxVolJobs INTEGER UNSIGNED DEFAULT 0,
   MaxVolFiles INTEGER UNSIGNED DEFAULT 0,
   MaxVolBytes BIGINT UNSIGNED DEFAULT 0,
   MaxPoolBytes BIGINT UNSIGNED DEFAULT 0,
   AutoPrune TINYINT DEFAULT 0,
   Recycle TINYINT DEFAULT 0,
   ActionOnPurge     TINYINT	DEFAULT 0,
   PoolType VARCHAR(20) NOT NULL,
   LabelType TINYINT DEFAULT 0,
   LabelFormat VARCHAR(128) NOT NULL,
   Enabled TINYINT DEFAULT 1,
   ScratchPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   RecyclePoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   NextPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   MigrationHighBytes BIGINT UNSIGNED DEFAULT 0,
   MigrationLowBytes BIGINT UNSIGNED DEFAULT 0,
   MigrationTime BIGINT UNSIGNED DEFAULT 0,
   UNIQUE (Name),
   PRIMARY KEY (PoolId)
   );


CREATE TABLE Client (
   ClientId INTEGER,
   Name VARCHAR(128) NOT NULL,
   Uname VARCHAR(255) NOT NULL,   -- uname -a field
   Plugins VARCHAR(1024) DEFAULT '',
   AutoPrune TINYINT DEFAULT 0,
   FileRetention BIGINT UNSIGNED DEFAULT 0,
   JobRetention  BIGINT UNSIGNED DEFAULT 0,
   UNIQUE (Name),
   PRIMARY KEY(ClientId)
   );

CREATE TABLE BaseFiles (
   BaseId BIGINT,
   BaseJobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   FileId INTEGER UNSIGNED REFERENCES File NOT NULL,
   FileIndex INTEGER DEFAULT 0,
   PRIMARY KEY(BaseId)
   );

CREATE INDEX basefiles_jobid_idx ON BaseFiles ( JobId );

CREATE TABLE UnsavedFiles (
   UnsavedId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PathId INTEGER UNSIGNED REFERENCES Path NOT NULL,
   Filename TEXT NOT NULL,
   PRIMARY KEY (UnsavedId)
   );


CREATE TABLE NextId (
   id INTEGER UNSIGNED DEFAULT 0,
   TableName TEXT NOT NULL,
   PRIMARY KEY (TableName)
   );



-- Initialize JobId to start at 1
INSERT INTO NextId (id, TableName) VALUES (1, 'Job');

CREATE TABLE Version (
   VersionId INTEGER UNSIGNED NOT NULL 
   );


CREATE TABLE Counters (
   Counter TEXT NOT NULL,     
   MinValue INTEGER DEFAULT 0, 
   MaxValue INTEGER DEFAULT 0,
   CurrentValue INTEGER DEFAULT 0,
   WrapCounter TEXT NOT NULL,
   PRIMARY KEY (Counter)
   );

CREATE TABLE CDImages (
   MediaId INTEGER UNSIGNED NOT NULL,
   LastBurn DATETIME NOT NULL,
   PRIMARY KEY (MediaId)
   );

CREATE TABLE PathHierarchy
(
     PathId integer NOT NULL,
     PPathId integer NOT NULL,
     CONSTRAINT pathhierarchy_pkey PRIMARY KEY (PathId)
);

CREATE INDEX pathhierarchy_ppathid 
	  ON PathHierarchy (PPathId);

CREATE TABLE PathVisibility
(
      PathId integer NOT NULL,
      JobId integer NOT NULL,
      Size int8 DEFAULT 0,
      Files int4 DEFAULT 0,
      CONSTRAINT pathvisibility_pkey PRIMARY KEY (JobId, PathId)
);

CREATE INDEX pathvisibility_jobid
	  ON PathVisibility (JobId);


CREATE TABLE Snapshot (
  SnapshotId	  INTEGER PRIMARY KEY AUTOINCREMENT,
  Name		  text NOT NULL,
  JobId 	  integer default 0,
  FileSetId	  integer default 0,
  CreateTDate	  bigint default 0,
  CreateDate	  datetime not null,
  ClientId	  int default 0,
  Volume	  text not null,
  Device	  text not null,
  Type		  text not null,
  Retention	  int default 0,
  Comment	  text
);

CREATE UNIQUE INDEX snapshot_idx ON Snapshot (Device, Volume, Name);

CREATE TABLE Status (
   JobStatus CHAR(1) NOT NULL,
   JobStatusLong BLOB, 
   Severity INT,
   PRIMARY KEY (JobStatus)
   );

INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('C', 'Created, not yet running',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('R', 'Running',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('B', 'Blocked',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('T', 'Completed successfully', 10);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('E', 'Terminated with errors', 25);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('e', 'Non-fatal error',20);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('f', 'Fatal error',100);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('D', 'Verify found differences',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('A', 'Canceled by user',90);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('F', 'Waiting for Client',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('S', 'Waiting for Storage daemon',15);
INSERT INTO Status (JobStatus,JobStatusLong) VALUES
   ('m', 'Waiting for new media');
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('M', 'Waiting for media mount',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('l', 'Doing data despooling',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('L', 'Committing data (last despool)',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('s', 'Waiting for storage resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('j', 'Waiting for job resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('c', 'Waiting for client resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('d', 'Waiting on maximum jobs',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('t', 'Waiting on start time',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('u', 'Cloud upload',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('w', 'Cloud download',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('p', 'Waiting on higher priority jobs',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('q', 'Queued waiting for device',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('a', 'SD despooling attributes',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('i', 'Doing batch insert file records',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('I', 'Incomplete Job',25);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('W', 'Terminated normally with warnings',25);

-- Initialize Version		 
INSERT INTO Version (VersionId) VALUES (1026);

PRAGMA default_cache_size = 100000;
PRAGMA synchronous = NORMAL;

END-OF-DATA

echo ""
echo "WARNING: !!!! SQLite3 is no longer supported. !!!!"
echo "WARNING: !!!! Please switch to MySQL or PostgreSQL !!!!"
echo "WARNING: !!!!  as soon as possible. !!!!"
echo ""

chmod 640 ${db_name}.db
exit 0
